//
//  MTNearbyViewController.m
//  ShiShiBang
//
//  Created by songbaoqiang on 16/9/1.
//  Copyright © 2016年 motianjituan. All rights reserved.
//

#import "MTNearbyViewController.h"
#import "MTWaterFlowLayout.h"
#import <MJRefresh/MJRefresh.h>
#import <AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "MTChatViewController.h"
#import "MTAdressViewController.h"
#import "MTAdvertiseView.h"
#import "MTPhotoCell.h"
#import "MTPhotoesCell.h"
#import "MTDetailOrderController.h"

static NSString *const ID = @"photo";
@interface MTNearbyViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,MTWaterFlowLayoutDelegate>

@property (nonatomic , weak) UICollectionView *collectionView;
@property (nonatomic , strong) NSMutableArray *photoArray;
@property (nonatomic, strong) MTAdvertiseView *adView;
@property (nonatomic , strong) NSMutableArray *titlearray;
@property (nonatomic , assign) int page;
@end

@implementation MTNearbyViewController

-(NSMutableArray *)photoArray {
    if (!_photoArray) {
        _photoArray = [NSMutableArray array];
    }
    return _photoArray;
}

- (void)viewDidLoad {

    [self initTopUI];
    self.titlearray = @[@"第一组",@"第二组",@"第3组"];
    [self initNetWorking];
    [self initCollection];
    [self initNavigationbar];
    [self setupRefreshView];
}
//集成刷新控件
#pragma mark - 添加上下拉刷新
- (void)setupRefreshView
{
    // 下拉刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUserData)];
    self.collectionView.mj_header = header;
    
    // 上拉刷新
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUserData)];
    footer.automaticallyHidden = YES;
    self.collectionView.mj_footer = footer;
    
}

- (void)loadNewUserData
{
     self.page = 1;
#pragma mark 网络请求
//    -(void)requestNet
//    {
//        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//        dic[@"page"] = [NSString stringWithFormat:@"%d",self.page];
//        NSString *urlstr = [NSString stringWithFormat:@"http://api.huceo.com/%@/other/?key=c32da470996b3fdd742fabe9a2948adb&num=20",self.content];
//        [mgr GET:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//            
//            NSArray *dataarray = [NewData objectArrayWithKeyValuesArray:responseObject[@"newslist"]];
//            // 创建frame模型对象
//            NSMutableArray *statusFrameArray = [NSMutableArray array];
//            for (NewData *data in dataarray) {
//                NewDataFrame *dataFrame = [[NewDataFrame alloc] init];
//                // 传递微博模型数据
//                dataFrame.NewData = data;
//                [statusFrameArray addObject:dataFrame];
//            }
//            [self.totalArray addObjectsFromArray:statusFrameArray];
//            self.page++;
//            // 刷新表格
//            [self.tableview reloadData];
//            
//            [self.tableview.header endRefreshing];
//            
//        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
//            
//        }];
//    }
}

-(void)loadMoreUserData {
//    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    dic[@"page"] = [NSString stringWithFormat:@"%d",self.page];
//    NSString *urlstr = [NSString stringWithFormat:@"http://api.huceo.com/%@/other/?key=c32da470996b3fdd742fabe9a2948adb&num=20",self.content];
//    [mgr GET:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        
//        NSArray *dataarray = [NewData objectArrayWithKeyValuesArray:responseObject[@"newslist"]];
//        // 创建frame模型对象
//        NSMutableArray *statusFrameArray = [NSMutableArray array];
//        for (NewData *data in dataarray) {
//            NewDataFrame *dataFrame = [[NewDataFrame alloc] init];
//            // 传递微博模型数据
//            dataFrame.NewData = data;
//            [statusFrameArray addObject:dataFrame];
//        }
//        [self.totalArray addObjectsFromArray:statusFrameArray];
//        self.page++;
//        // 刷新表格
//        [self.tableview reloadData];
//        
//        [self.tableview.header endRefreshing];
//        
//    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
//        
//    }];
//    [self.tableview.footer endRefreshing];
}

-(void)initNetWorking
{
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    dic[@"pn"] = @"1";
    dic[@"rn"] = @6;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSString *urlstr = [NSString stringWithFormat:@"http://image.baidu.com/wisebrowse/data?tag1=%@&tag2=%@",@"美女",@"小清新"];
    urlstr = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",urlstr);

    [mgr GET:urlstr parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *dataarray = [MTPhotoItem objectArrayWithKeyValuesArray:responseObject[@"imgs"]];
                // 创建frame模型对象
                NSMutableArray *statusFrameArray = [NSMutableArray array];
                for (MTPhotoItem *photo in dataarray) {
                    [statusFrameArray addObject:photo];
                }
        
                if (dataarray.count) {
                    [self.photoArray removeAllObjects];
                }
                [self.photoArray addObjectsFromArray:statusFrameArray];
        
//                self.pn += 60;
                      // 刷新表格
                [self.collectionView reloadData];
//                [self.collectionView.header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@", error);
    }];
}

-(void)initCollection {
    
    MTWaterFlowLayout *layout = [[MTWaterFlowLayout alloc]init];
    layout.columnsCount = 2;
    layout.delegate = self;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    collectionView.backgroundColor = UIColorFromRGB(0xeeeeee);
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [collectionView registerNib:[UINib nibWithNibName:@"MTPhotoesCell" bundle:nil] forCellWithReuseIdentifier:ID];
    [collectionView addSubview:_adView];
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
   
}

-(void)initTopUI {
    MTAdvertiseView *adView = [MTAdvertiseView loadXib];
    _adView = adView;
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(changeTitle) userInfo:nil repeats:YES];
    
}

static int i = 0 ;
-(void)changeTitle {
    i++;
    if (i >= self.titlearray.count) {
        i = 0;
    }
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.titlearray[i]];
    [str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x379f48) range:NSMakeRange(0,2)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(2,1)];
    self.adView.advertiseBtn.titleLabel.attributedText = str;
}

#pragma mark - <MTWaterflowLayoutDelegate>
- (CGFloat)waterflowLayout:(MTWaterFlowLayout *)waterflowLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath
{
    MTPhotoItem *photo = self.photoArray[indexPath.item];
    NSString *title = photo.title;

    NSDictionary *attributes =@{NSFontAttributeName:[UIFont systemFontOfSize:12]};
    CGSize textSize = [title boundingRectWithSize:CGSizeMake(155,2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    NSInteger height = photo.small_height / photo.small_width * width + textSize.height + 111;
    NSLog(@"label:%ld----%ld--%f", height, indexPath.row, photo.small_height / photo.small_width * width);
    return height;
}

#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.photoArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MTPhotoesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    cell.photo = self.photoArray[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MTDetailOrderController *vc = [[MTDetailOrderController alloc] init];
    
//    PhotoShowViewController *photoShow = [[PhotoShowViewController alloc]init];
//    photoShow.currentIndex = (int)indexPath.row;
//    photoShow.mutaArray = self.photoArray;
//    NSLog(@"%@",self.photoArray);
     [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark ------点击跳转界面
-(void)adressClick {
    MTAdressViewController *vc = [[MTAdressViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)chatClick {
      MTChatViewController *vc = [MTChatViewController shareChatViewController];
     [self.navigationController pushViewController:vc animated:YES];
    NSLog(@"one----%@",vc);

}

- (void)viewDidLayoutSubviews {
    _adView.frame = CGRectMake(0, 0, MTScreenW, 44);
}
#pragma mark ------设置导航条状态栏
-(void)initNavigationbar {
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"iocn_address"] highImage:[UIImage imageNamed:@"iocn_address_ press"] target:self action:@selector(adressClick)];
    self.navigationItem.title = @"实事帮";
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"news"] highImage:[UIImage imageNamed:@"news_gray"] target:self action:@selector(chatClick)];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:UIColorFromRGB(0x45c75a)]  forBarMetrics:UIBarMetricsDefault];
    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
    attr[NSFontAttributeName] = [UIFont boldSystemFontOfSize:17];
    attr[NSForegroundColorAttributeName] = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:attr];
}

- (void)viewWillAppear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
@end